package com.me.chat.util.img.gif;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @Author: qiu
 * @Date: 2021/4/25 14:23
 */
public class GifUtil {

    private final static String extension = "gif";

    /**
     * gif 缩略图工具类
     * @param bytes
     * @param width
     * @param height
     * @return
     * @throws IOException
     */
    public static ByteArrayOutputStream generateGif(byte[] bytes,int width,int height) {
        //将得到的 byte 转化未 输入流
        InputStream byteArr = new ByteArrayInputStream(bytes);
        ByteArrayOutputStream output = null;
        try {
            output = new ByteArrayOutputStream();
            //将MultipartFile内容读出来
            GifDecoder decoder = new GifDecoder();
            //解码器阅读 输入流
            decoder.read(byteArr);

            //编译器重构 解码器每一帧
            AnimatedGifEncoder encoder = new AnimatedGifEncoder();
            //目标文件
            encoder.start(output);
            //不断重复
            encoder.setRepeat(0);

            //得到帧数
            int frameCount = decoder.getFrameCount();
            //循环，重构每一个帧
            for (int i=0; i<frameCount; i++) {
                //用源文件的延迟来定义新文件的延迟
                encoder.setDelay(decoder.getDelay(i));
                //缩略图片
                BufferedImage image = zoom(decoder.getFrame(i), width , height);
                //往动画中添加
                encoder.addFrame(image);
            }
            //完成gif的编译
            encoder.finish();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(output != null){
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(byteArr != null){
                try {
                    byteArr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return output;
    }


    /**
     * BufferedImage 缩略
     * @param sourceImage
     * @param width
     * @param height
     * @return
     */
    private static BufferedImage zoom(BufferedImage sourceImage , int width , int height){
        BufferedImage zoomImage = new BufferedImage(width, height, sourceImage.getType());
        Image image = sourceImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        Graphics gc = zoomImage.getGraphics();
        gc.setColor(Color.WHITE);
        gc.drawImage( image , 0, 0, null);
        return zoomImage;
    }
}
